Grokking SQL for Tech Interviews
Rate this course
Ask Author
Contribute
Back to course home

1% completed

Vote For New Content
Introduction
Course Overview
What is RDBMS?
What is SQL?
A Quick Review of SQL
Read data from table
WHERE Clause
Operators
Handle NULLs in SQL
DISTINCT Clause
ORDER BY Clause
LIMIT and OFFSET
GROUP BY
HAVING
Aggregate Functions
Order of Execution
Order of SQL Query Execution
SQL Functions
Number Functions
String Functions
Date Functions
Nested Queries
Nested Query
Types of Subqueries
JOINS
Introduction
INNER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
SELF JOIN
SET Operations
What are SET operations?
UNION
INTERSECT
EXCEPT
A Quick Review of DDL
Keys in SQL
CREATE
ALTER
DROP
TRUNCATE
Indexes
A Quick Review of DML
INSERT
UPDATE
DELETE
Database Backup & Restore
Backup Database
Restore Database
Interview Problems - Easy
1. Major Cities
2. Not boring movies
3. Triangle Judgement
4. Biggest Single Number
5. Product Sales Analysis I
6. Product Sales Analysis II
7. Game Play Analysis I
8. Game Play Analysis II
9. Queries Quality and Percentage
10. Average Selling Price
11. Weather Type in Each Country
12. Students and Examinations
13. Ads Performance
14. Group Sold Products By The Date
15. Employee Email Verification
16. Sellers With No Sales
17. Average Time of Process
18. Find Followers Count
19. Ad-Free Sessions
20. Bikes Last Time Used
21. Daily User Engagement Levels
22. Employee Attendance Record
23. Library Book Loans
24. Customer Purchase Summary
25. Long Comments (Easy)
26. Unused Accounts
27. Patient Appointment No-Shows
28. Books and Authors
29. High School Attendance
30. Employee Absences
31. Green Product Identification (Easy)
32. Employee Department Exclusion (Easy)
33. Sales Person (Easy)
34. Employee Task Tracking (Easy)
Interview Problems - Medium
1. Winning Candidate
2. Second Degree Follower
3. 2nd Highest Salary
4. Game Play Analysis III
5. Game Play Analysis IV
6. Active Businesses
7. Product Price on a Specific Date
8. Monthly Transactions II
9. Team Scores in Football Tournament
10. Page Recommendations
11. Running Total for Different Genders
12. Evaluate Boolean Expression
13. Active Users
14. Find Interview Candidates
15. Suspicious Bank Accounts
16. Order Fulfillment Rate (Medium)
17. Last Person to Fit in the Elevator (Medium)
18. Retail Expansion Analysis (Medium)
19. Employee Collaboration Networks (Medium)
20. Second Fastest Time in Races (Medium)
Interview Problems - Hard
1. Trips and Users
2. Human Traffic of Stadium
3. Students Report By Geography
4. Game Play Analysis V
5. Number of Transactions per Visit
6. Find the Quiet Students in All Exams
7. First and Last Call On the Same Day
8. Build the Equation
9. Longest Winning Streak
10. Dynamic Pivoting of a Table
11. Dynamic Unpivoting of a Table
12. Generate the Invoice
13. Popularity Percentage
14. Viewers Turned Streamers
15. Status of Flight Tickets
Test Your Knowledge
1. High Performing Employees (Easy)
2. Student Course Averages (Easy)
3. Library Book Checkout Percentage (Easy)
4. Employee Performance and Improvement Rate (Easy)
5. Find Popular Posts (Easy)
6. Main Office Assignment for Each Employee (Easy)
7. Rectangle Validation (Easy)
8. Library Book Checkouts by Date (Easy)
9. Same-Day Appointment Fulfillment (Medium)
10. Departments with High Earning Employees (Medium)
11. Students Who Attended All Courses (Medium)
12. Library Book Checkouts First Year (Medium)
13. Repeated Values in Sequence (Medium)
14. School Top Achievers by Subject (Hard)
14. School Top Achievers by Subject (Hard)

Problem Statement

Table: Student
Each row in this table represents a student's performance in a specific subject, including their unique ID, name, score, and the subject ID they were evaluated in.

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| score       | int     |
| subjectId   | int     |
+-------------+---------+
id is the primary key for this table.
subjectId is a foreign key referencing the id from the Subject table.

Table: Subject
This table lists all subjects offered, each with a unique ID and name.

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
id is the primary key for this table.

Develop a solution to identify the top achievers in each subject, defined as students with scores in the top three unique scores for that subject.

Example

Input:

Student table: +----+--------+-------+-----------+ | id | name | score | subjectId | +----+--------+-------+-----------+ | 1 | Alice | 92 | 1 | | 2 | Bob | 85 | 2 | | 3 | Carol | 87 | 2 | | 4 | Derek | 95 | 1 | | 5 | Elisa | 88 | 1 | | 6 | Fiona | 92 | 1 | | 7 | George | 90 | 1 | +----+--------+-------+-----------+ Subject table: +----+---------+ | id | name | +----+---------+ | 1 | Math | | 2 | Science | +----+---------+

Output:

+---------+---------+-------+ | Subject | Student | Score | +---------+---------+-------+ | Math | Derek | 95 | | Math | Alice | 92 | | Math | Fiona | 92 | | Math | George | 90 | | Science | Carol | 87 | | Science | Bob | 85 | +---------+---------+-------+

In this example, the top achievers in each subject are determined based on their scores, with a maximum of three students recognized per subject if there are at least three unique scores.

Try It Yourself

MYSQL

. . . .

Student =

Subject =

Solution

To identify the top achievers in each subject, defined as students with scores in the top three unique scores for that subject, we can utilize SQL's window functions, specifically DENSE_RANK(). This approach allows us to rank students based on their scores within each subject and then filter out those who fall within the top three ranks.

  • Join Tables: Combine the Student and Subject tables to associate each student's performance with the corresponding subject name.
  • Rank Scores Within Each Subject: Use the DENSE_RANK() window function to assign ranks to students based on their scores in descending order within each subject.
  • Filter Top Achievers: Select students whose ranks are within the top three for their respective subjects.
  • Order the Results: Sort the final output by subject name and rank for organized presentation.

SQL Query

WITH RankedScores AS ( SELECT st.name AS Student, su.name AS Subject, st.score, DENSE_RANK() OVER (PARTITION BY st.subjectId ORDER BY st.score DESC) AS s_rank FROM Student st JOIN Subject su ON st.subjectId = su.id ) SELECT Subject, Student, score AS Score FROM RankedScores WHERE s_rank <= 3 ORDER BY Subject, s_rank;

Step-by-Step Approach

Step 1: Join Student and Subject Tables and Rank Scores

Combine the Student and Subject tables to associate each student's score with the corresponding subject. Then, rank the students within each subject based on their scores in descending order.

SQL Query:

WITH RankedScores AS ( SELECT st.name AS Student, su.name AS Subject, st.score, DENSE_RANK() OVER (PARTITION BY st.subjectId ORDER BY st.score DESC) AS s_rank FROM Student st JOIN Subject su ON st.subjectId = su.id )

Explanation:

  • WITH RankedScores AS (...):
    • Defines a Common Table Expression (CTE) named RankedScores to store the intermediate results.
  • SELECT st.name AS Student, su.name AS Subject, st.score, DENSE_RANK() OVER (...) AS s_rank:
    • st.name AS Student & su.name AS Subject:
      • Selects the student's name and the subject's name, renaming them for clarity in the results.
    • st.score:
      • Retrieves the student's score in the subject.
    • DENSE_RANK() OVER (PARTITION BY st.subjectId ORDER BY st.score DESC) AS s_rank:
      • Assigns a rank to each student within their subject based on their score.
      • PARTITION BY st.subjectId:
        • Ensures that ranking restarts for each subject.
      • ORDER BY st.score DESC:
        • Orders the scores in descending order so that the highest score receives the top rank.
      • DENSE_RANK():
        • Assigns the same rank to students with identical scores, ensuring that ranks are consecutive without gaps.
  • FROM Student st JOIN Subject su ON st.subjectId = su.id:
    • Performs an inner join between the Student and Subject tables based on the subjectId to link each student's performance to the corresponding subject.

Output After Step 1:

Assuming the example input, the RankedScores CTE would produce:

+---------+---------+-------+--------+ | Student | Subject | score | s_rank | +---------+---------+-------+--------+ | Derek | Math | 95 | 1 | | Alice | Math | 92 | 2 | | Fiona | Math | 92 | 2 | | George | Math | 90 | 3 | | Elisa | Math | 88 | 4 | | Carol | Science | 87 | 1 | | Bob | Science | 85 | 2 | +---------+---------+-------+--------+

Step 2: Select Top Achievers Based on Rank

Retrieve the students who have ranks within the top three for their respective subjects, indicating they are among the top achievers.

SQL Query:

SELECT Subject, Student, score AS Score FROM RankedScores WHERE s_rank <= 3 ORDER BY Subject, s_rank;

Explanation:

  • SELECT Subject, Student, score AS Score:
    • Chooses the subject name, student name, and their score for the final output.
  • FROM RankedScores:
    • Utilizes the previously defined CTE RankedScores to access the ranked data.
  • WHERE s_rank <= 3:
    • Filters the records to include only those students whose rank is 3 or below within their subject, effectively selecting the top three unique scores.
  • ORDER BY Subject, s_rank:
    • Sorts the results first by subject name and then by rank to present the top achievers in an organized manner.

Final Output:

Based on the example input, the final output would be:

+---------+---------+-------+ | Subject | Student | Score | +---------+---------+-------+ | Math | Derek | 95 | | Math | Alice | 92 | | Math | Fiona | 92 | | Math | George | 90 | | Science | Carol | 87 | | Science | Bob | 85 | +---------+---------+-------+
13. Repeated Values in Sequence (Medium)
Mark as Completed

On this page

Problem Statement

Example

Try It Yourself

Solution

SQL Query

Step-by-Step Approach